package com.hjy.core.handler;

import com.hjy.common.entity.RpcRequest;
import com.hjy.common.entity.RpcResponse;
import com.hjy.common.enumeration.ResponseCode;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 通过反射进行方法调用
 */
public class RequestHandler {
    /**
     * 根据服务对象, 执行对应的远程方法
     * @param rpcRequest 请求包装对象
     * @param service 服务对象
     * @return 服务返回值
     */
    public Object handle(RpcRequest rpcRequest, Object service) {
        Object result = null;
        try {
            result = invokeTargetMethod(rpcRequest, service);
            System.out.println("服务:"+rpcRequest.getInterfaceName()+" 成功调用方法:"+rpcRequest.getMethodName());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 获取方法执行返回值
     * @param rpcRequest
     * @param service
     * @return
     */
    private Object invokeTargetMethod(RpcRequest rpcRequest, Object service) {
        try {
            Method method = service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamTypes());
            return method.invoke(service,rpcRequest.getParameters());
        } catch (NoSuchMethodException e) {
            return RpcResponse.fail(ResponseCode.METHOD_NOT_FOUND);
        } catch (InvocationTargetException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }
}
